﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Win32;
using IWshRuntimeLibrary;

namespace update_install
{
    class Program
    {
        //安装文件更新下载地址
        static string url_app = System.Configuration.ConfigurationManager.AppSettings["url_app"];
        //安装文件版本检查地址
        static string url_version = System.Configuration.ConfigurationManager.AppSettings["url_version"];
        //app 名称
        static string appName = "MyToolsDemo";
        //app 解压后存放地址
        static string save_dir = @"D:\scxd_apps\" + appName;
        //app 下载后存放地址
        static string des_file = @"D:\scxd_apps\"+ appName + ".rar";
        //app 完全路径
        static string appPath = @"D:\scxd_apps\MyToolsDemo\" + appName + ".exe";

        static void Main(string[] args)
        {
            //判断是否已经存在指定路径的程序
            if (System.IO.File.Exists(appPath))
            {
                bool isUpdate = false;
                try
                {
                    isUpdate = CheckUpdate(appPath);
                }
                catch (Exception e)
                {
                    //更新异常处理
                    ProcUpdateException(appPath, e);
                    return;
                }
                if (isUpdate)
                {
                    //需要更新，进行下载操作
                    //不存在程序的时候，直接下载程序
                    DownLoad(des_file);
                    //解压程序包
                    UnRAR(des_file, save_dir);
                }
                //启动程序
                StartApp(appPath);
                return;
            }
            //不存在程序的时候，直接下载程序
            DownLoad(des_file);
            //解压程序包
            UnRAR(des_file, save_dir);

            //IE文件夹copy
            Copy(@"C:\Program Files (x86)\Internet Explorer", save_dir);
            //创建桌面快捷方式
            //CreateShortcutOnDesktop("tool", appPath);

            //启动程序
            StartApp(appPath);
            //Console.ReadKey();
        }

        /// <summary>
        /// 更新异常处理
        /// </summary>
        /// <param name="appPath"></param>
        /// <param name="e"></param>
        private static void ProcUpdateException(string appPath, Exception e)
        {
            Console.WriteLine("更新程序异常： " + e.Message);
            Console.WriteLine("******************************************************");
            Console.WriteLine("是否继续启动程序？【 Y:不更新并继续启动程序； N:退出程序 】");
            while (true)
            {
                Console.WriteLine("请输入Y/N:");
                string input = Console.ReadLine().Trim();
                if (string.Compare(input, "Y", true) == 0 || string.Compare(input, "yes", true) == 0)
                {
                    StartApp(appPath);
                    return;
                }
                else if (string.Compare(input, "N", true) == 0 || string.Compare(input, "no", true) == 0)
                {
                    System.Environment.Exit(0);
                }
                else
                {
                    Console.WriteLine("输入错误，请重新输入！【 Y:不更新并继续启动程序； N:退出程序 】");
                }
            }
        }

        /// <summary>
        /// 根据应用程序地址启动程序
        /// </summary>
        /// <param name="appPath"></param>
        static void StartApp(string appPath)
        {
            try
            {
                Process.Start(appPath);
            }
            catch (Exception e)
            {
                Console.WriteLine("程序启动失败：" + e.Message);
                Console.ReadKey();
            }
        }

        /// <summary>
        /// 检查程序是否需要更新
        /// </summary>
        /// <param name="appPath"></param>
        static bool CheckUpdate(string appPath)
        {
            bool res = false;
            try
            {
                //throw new Exception("更新程序时，服务端发生异常：Test");
                // 获取当前正在使用的版本
                FileVersionInfo fv = FileVersionInfo.GetVersionInfo(appPath);
                Version curVersion = new Version(fv.FileVersion);
                //发起请求获取 服务端版本,判断是否需要更新
                string msg = Http(url_version + "?preVersion=" + curVersion, EHttpMethod.GET);
                Regex reg = new Regex("^[0|1]{1}$");
                if (reg.IsMatch(msg))
                {
                    res = msg == "1";//1 表示需要更新程序
                }
                else
                {
                    //服务端异常出现
                    Console.WriteLine(msg);
                    throw new Exception("更新程序时，服务端发生异常：" + msg);
                }
            }
            catch (Exception)
            {
                throw;
            }
            return res;
        }

        /// <summary>
        /// 发送 http 请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="httpHMthod"></param>
        /// <returns></returns>
        static string Http(string url,EHttpMethod httpHMthod)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = httpHMthod == EHttpMethod.GET ? "get" : "post";
            string msg = string.Empty;
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                using (Stream stream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        msg = reader.ReadToEnd();
                    }
                }
            }
            return msg;
        }

        /// <summary>
        /// 下载文件到指定位置
        /// </summary>
        /// <param name="savePath"></param>
        static void DownLoad(string savePath)
        {
            string dir = Path.GetDirectoryName(savePath);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            WebClient client = new WebClient();
            //异步下载
            //client.DownloadFileCompleted += Client_DownloadFileCompleted;
            //client.DownloadProgressChanged += Client_DownloadProgressChanged;
            //client.DownloadFileAsync(new Uri(url_app), savePath);
            
            //同步下载
            client.DownloadFile(new Uri(url_app), savePath);
        }

        /// <summary>
        /// 异步下载事件绑定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void Client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            Console.WriteLine("*******************************");
            Console.WriteLine(e.BytesReceived*1.0/ e.TotalBytesToReceive*100+"%");
            Console.WriteLine(e.BytesReceived);
            Console.WriteLine(e.TotalBytesToReceive);
            Console.WriteLine("*******************************");
        }
        /// <summary>
        /// 异步下载完成事件绑定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void Client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            Console.WriteLine(e.UserState);
        }

        /// <summary>
        /// 判断是否安装解压软件
        /// </summary>
        /// <returns></returns>
        static string ExistRar()
        {
            RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe");

            string strKey = key.GetValue("").ToString();

            return strKey;
        }
        /// <summary>  
        /// 解压RAR文件  
        /// </summary>  
        /// <param name="rarFilePath">要解压的文件路径</param>  
        /// <param name="unrarDestPath">解压路径（绝对路径）</param>  
        public static void UnRAR(string rarFilePath, string unrarDestPath)
        {
            string rarexe = ExistRar();
            if (String.IsNullOrEmpty(rarexe))
            {
                throw new Exception("未安装WinRAR程序。");
            }
            try
            {
                //组合出需要shell的完整格式  
                string shellArguments = string.Format("x -o+ \"{0}\" \"{1}\\\"", rarFilePath, unrarDestPath);

                //用Process调用  
                using (Process unrar = new Process())
                {
                    ProcessStartInfo startinfo = new ProcessStartInfo();
                    startinfo.FileName = rarexe;
                    startinfo.Arguments = shellArguments;               //设置命令参数  
                    startinfo.WindowStyle = ProcessWindowStyle.Hidden;  //隐藏 WinRAR 窗口  

                    unrar.StartInfo = startinfo;
                    unrar.Start();
                    unrar.WaitForExit();//等待解压完成  

                    unrar.Close();
                }
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 复制文件内容到指定文件夹
        /// </summary>
        /// <param name="src_path"></param>
        /// <param name="des_path"></param>
        static void Copy(string src_path,string des_path)
        {
            if(des_path[des_path.Length-1] != Path.DirectorySeparatorChar)
            {
                des_path += Path.DirectorySeparatorChar;
            }

            if (!Directory.Exists(des_path))
            {
                Directory.CreateDirectory(des_path);
            }
            string[] files = Directory.GetFileSystemEntries(src_path);
            foreach (var f in files)
            {
                if (f.EndsWith(".exe"))
                {
                    continue;
                }
                if (Directory.Exists(f))
                {
                    Copy(f, des_path + Path.GetFileName(f));
                }
                else
                {
                    System.IO.File.Copy(f, des_path + Path.GetFileName(f), true);
                }
            }
        }

        //需要引入IWshRuntimeLibrary，搜索Windows Script Host Object Model

        /// <summary>
        /// 创建快捷方式
        /// </summary>
        /// <param name="directory">快捷方式所处的文件夹</param>
        /// <param name="shortcutName">快捷方式名称</param>
        /// <param name="targetPath">目标路径</param>
        /// <param name="description">描述</param>
        /// <param name="iconLocation">图标路径，格式为"可执行文件或DLL路径, 图标编号"，
        /// 例如System.Environment.SystemDirectory + "\\" + "shell32.dll, 165"</param>
        /// <remarks></remarks>
        public static void CreateShortcut(string directory, string shortcutName, string targetPath,
            string description = null, string iconLocation = null)
        {
            if (!System.IO.Directory.Exists(directory))
            {
                System.IO.Directory.CreateDirectory(directory);
            }

            string shortcutPath = Path.Combine(directory, string.Format("{0}.lnk", shortcutName));
            WshShell shell = new WshShell();
            IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);//创建快捷方式对象
            shortcut.TargetPath = targetPath;//指定目标路径
            shortcut.WorkingDirectory = Path.GetDirectoryName(targetPath);//设置起始位置
            shortcut.WindowStyle = 1;//设置运行方式，默认为常规窗口
            shortcut.Description = description;//设置备注
            shortcut.IconLocation = string.IsNullOrWhiteSpace(iconLocation) ? targetPath : iconLocation;//设置图标路径
            shortcut.Save();//保存快捷方式
        }

        /// <summary>
        /// 创建桌面快捷方式
        /// </summary>
        /// <param name="shortcutName">快捷方式名称</param>
        /// <param name="targetPath">目标路径</param>
        /// <param name="description">描述</param>
        /// <param name="iconLocation">图标路径，格式为"可执行文件或DLL路径, 图标编号"</param>
        /// <remarks></remarks>
        public static void CreateShortcutOnDesktop(string shortcutName, string targetPath,
            string description = null, string iconLocation = null)
        {
            string desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);//获取桌面文件夹路径
            CreateShortcut(desktop, shortcutName, targetPath, description, iconLocation);
        }


    }
}
